import axios from 'axios'
import { ElMessage } from 'element-plus'

const BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8000'

// 创建基础axios实例
const createAxiosInstance = (prefix: string = '', baseUrl: string = BASE_URL) => {
  const instance = axios.create({
    baseURL: `${baseUrl}${prefix}`,
    timeout: 10000,
    headers: {
      'Content-Type': 'application/json'
    }
  })

  // 请求拦截器
  instance.interceptors.request.use(
    (config) => {
      // 从localStorage获取token
      const token = localStorage.getItem('token')
      if (token) {
        config.headers.Authorization = `Bearer ${token}`
      }
      return config
    },
    (error) => {
      return Promise.reject(error)
    }
  )

  // 响应拦截器
  instance.interceptors.response.use(
    (response) => {
      // 添加日志记录
      console.log(`API响应 [${response.config.method?.toUpperCase()}] ${response.config.url}:`, response.data)
      // 直接返回响应数据
      return response.data
    },
    (error) => {
      if (error.response) {
        // 处理错误响应
        const message = error.response.data.detail || error.response.data.message || '请求失败'
        console.error(`API错误 [${error.config?.method?.toUpperCase()}] ${error.config?.url}:`, error.response.data)
        ElMessage.error(message)
        
        // 处理401未授权
        if (error.response.status === 401) {
          localStorage.removeItem('token')
          window.location.href = '/login'
        }
      } else {
        console.error('网络错误:', error)
        ElMessage.error('网络错误，请检查网络连接')
      }
      return Promise.reject(error)
    }
  )

  return instance
}

export default createAxiosInstance

// 创建各种API服务实例
export const statisticsApi = createAxiosInstance('/api/statistics') 